package com.uminho.egendmeprofessional;

import java.util.Date;
import java.util.GregorianCalendar;
import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.markupartist.android.widget.ActionBar;
import com.markupartist.android.widget.ActionBar.Action;
import com.uminho.exceptions.InvalidOAuthParametersError;
import com.uminho.exceptions.InvalidOAuthTokenError;
import com.uminho.http.Webservice;
import com.uminho.objects.Service;
import com.uminho.service.ServiceCalendar;
import com.uminho.service.ServiceDay;
import com.uminho.tools.Disponibilidades;

/****c* egendme/ServicoActivity
 * DESCRIPTION
 * Classe responsável por oferecer suporte à actividade ServicoActivity
 *
 ****
 */

public class ServicoActivity extends Activity {
	private long serviceId=-1;
	private long bookmarkId=-1;
	private String serviceType="";
	private Service servico=null;
	ProgressDialog myProgressDialog = null; 
	Handler messages;
	ListView listView;
	Button buttonAddFromFavorites, buttonRemoveFromFavorites, buttonAssign, seeServiceCalendar;
	//date piker
	int mYear;
    int mMonth;
    int mDay;
    static final int DATE_DIALOG_ID = 0;
    
	
	/****f* ServicoActivity/onCreate
	 * DESCRIPTION
	 * Método executado para criar a actividade
	 * INPUTS
	 * Estado da aplicação
	 * RESULT
	 * Actividade criada
	 *
	 ****
	 */
	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.servico);		
		
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setHomeAction(new Action() {
			
			public void performAction(View view) {
				setResult(4);
				finish();
			}
			
			public int getDrawable() {
				return R.drawable.icon1;
			}
		});
		actionBar.setTitle(R.string.favorite_action_title);
		
		//init handler
	    initHandler();
	    
	    //set service id
		Bundle b = getIntent().getExtras();
		long sid = b.getLong("servicokey", -1);
		bookmarkId=b.getLong("bookmarkey", -1);
		serviceType=b.getString("servicoType");
		serviceId=sid;
		
		if(serviceId!=-1)
			initServico();		
		else initEmptyServico();
		
		
	}
	public void setServiceId(long l){
		serviceId=l;
	}
	private void initEmptyServico() {
		messages.sendEmptyMessage(-1);
		
	}
	
	/****f* ServicoActivity/initServico
	 * DESCRIPTION
	 * Método executado para receber o serviço desejado
	 * INPUTS
	 * Id do serviço
	 * RESULT
	 * recebido serviço respectivo
	 *
	 ****
	 */
	private void initServico(){
		myProgressDialog = ProgressDialog.show(this,getString(R.string.loading), getString(R.string.getService), true); 

		Thread a = new Thread() {

			@Override
			public void run() {

				Webservice w = Webservice.getInstance();
				try{
					servico=w.getService(serviceId);
				}catch (InvalidOAuthTokenError e) {
					messages.sendEmptyMessage(-15);
					Log.d("Favorites", "token error loading bookmarks");
					return;
				}catch (InvalidOAuthParametersError e) {
					messages.sendEmptyMessage(-15);
					Log.d("Favorites", "autentication error loading bookmarks");
					return;
				
				}catch (Exception e){
					e.printStackTrace();
					messages.sendEmptyMessage(-16);
					initEmptyServico();
					return;
				}
				
				if(servico==null) Log.d("ServicoActivity", "Service é null!!!");
				// dismiss the progress dialog
				myProgressDialog.dismiss();
				messages.sendEmptyMessage(1);

			}

		};
		a.start();
		
	}
	
	/****f* ServicoActivity/initHandler
	 * DESCRIPTION
	 * Método executado para iniciar um handler
	 * RESULT
	 * Handler iniciado
	 *
	 ****
	 */
	private void initHandler(){
		messages = new Handler() {
	        @Override
			public void handleMessage(Message msg) {
	        	//empty
	        	if(msg.what==-1){
	        		Log.d("Servico", "error");
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		      
	        	}
	        	//success
	        	else if(msg.what==1){
	        		//buttons
	        		if(serviceType.equals("favorite")){
	        			//set main layout visible
	        			//LinearLayout generalLayout=(LinearLayout) findViewById(R.id.linearLayoutServicoGeral);
	        			//generalLayout.setVisibility(LinearLayout.VISIBLE);
	        			
	        			ImageView avatar = (ImageView) findViewById(R.id.imageAvatar);
	        			TextView desc, name, email, phone, mobilephone, website, address, category;
	        			LinearLayout ldesc, lname, lemail, lphone, lmobilephone, lwebsite, laddress, lcategory;
	        			/*
	        			desc = (TextView) findViewById(R.id.textDescription);
	        			name = (TextView) findViewById(R.id.title);
	        			email = (TextView) findViewById(R.id.textDescEmail);
	        			phone = (TextView) findViewById(R.id.textDescPhone);
	        			mobilephone = (TextView) findViewById(R.id.textDescMobilePhone);
	        			website = (TextView) findViewById(R.id.textDescWebsite);
	        			address = (TextView) findViewById(R.id.textDescAddress);
	        			category = (TextView) findViewById(R.id.textDescCategory);
	        			
	        			lname = (LinearLayout) findViewById(R.id.linearLayoutName);
	        			lemail = (LinearLayout) findViewById(R.id.linearLayoutEmail);
	        			lphone = (LinearLayout) findViewById(R.id.linearLayoutPhone);
	        			lmobilephone = (LinearLayout) findViewById(R.id.linearLayoutMobilePhone);
	        			lwebsite = (LinearLayout) findViewById(R.id.linearLayoutWebsite);
	        			laddress = (LinearLayout) findViewById(R.id.linearLayoutAddress);
	        			ldesc = (LinearLayout) findViewById(R.id.linearLayoutDescription);
	        			lcategory = (LinearLayout) findViewById(R.id.linearLayoutCategory);
	        			
	        			if(servico.getAvatar() != null) avatar.setImageDrawable(servico.getAvatar());
	        			
	        			if(!servico.getDescription().equals("")){
	        				desc.setText(servico.getDescription().toString());
//	        				ldesc.setVisibility(1);
	        			}
	        			if(servico.getName()!=null){
	        				name.setText(servico.getName().toString());
//	        				lname.setVisibility(LinearLayout.VISIBLE);
	        			}
	        			/*
	        			if(!servico.getCategory().equals("")){
	        				category.setText(servico.getCategory());
//	        				lcategory.setVisibility(LinearLayout.VISIBLE);
	        			}
	        			
	        			if(!servico.getEmail().equals("")){
	        				email.setText(servico.getEmail().toString());
//		        			lemail.setVisibility(LinearLayout.VISIBLE);
	        			}
	        			if(!servico.getPhone().equals("")){
	        				phone.setText(servico.getPhone().toString());
//		        			lphone.setVisibility(1);
	        			}
	        			if(!servico.getMobile_phone().equals("")){
	        				mobilephone.setText(servico.getMobile_phone().toString());
		        			mobilephone.setVisibility(1);
//		        			lmobilephone.setVisibility(1);
	        			}
	        			if(!servico.getWebsite().equals("")){
	        				website.setText(servico.getWebsite().toString());
		        			website.setVisibility(1);
//		        			lwebsite.setVisibility(1);
	        			}
	        			if(!servico.getAddress().equals("")){
	        				address.setText(servico.getAddress().toString());
		        			address.setVisibility(1);
//		        			laddress.setVisibility(1);
	        			}
	        			
	        			*/
	        			/*//task lable
	        			RelativeLayout relTask = new RelativeLayout(ServicoActivity.this);
	        			relTask.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
	        			relTask.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
	        			TextView textview = new TextView(ServicoActivity.this);
	        	        textview.setText(getString(R.string.task_lable));
	        	        textview.setTextColor(Color.YELLOW);
	        	        relTask.addView(textview);
	        	        //resource lable
	        			RelativeLayout relResource = new RelativeLayout(ServicoActivity.this);
	        			relResource.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
	        			relResource.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
	        			TextView textview2 = new TextView(ServicoActivity.this);
	        			textview2.setText(getString(R.string.resource_lable));
	        	        textview2.setTextColor(Color.YELLOW);
	        	        relResource.addView(textview2);
	        	        
	        			LinearLayout lLayout = (LinearLayout)findViewById(R.id.task_resources_layout);
	        			
        			    lLayout.addView(relTask);
        			    
        			    
    			    	
    			    	for(int i = 1; i <5; i++) {
	        			     //inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	        			     //inflater.inflate(R.layout.singletextline, lLayout);
    			    		LinearLayout linha = new LinearLayout(ServicoActivity.this);
        			    	linha.setLayoutParams(new LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
        			    	linha.setOrientation(0);
    			    		TextView esquerda = new TextView (ServicoActivity.this);
        			    	esquerda.setText("left");
        			    	esquerda.setGravity(Gravity.LEFT);
        			    	linha.addView(esquerda);
        			    	TextView direita = new TextView (ServicoActivity.this);
        			    	direita.setText("right");
        			    	direita.setGravity(Gravity.RIGHT);
        			    	linha.addView(direita);
        			    	lLayout.addView(linha);
        			    	
	        			}
        			    
        			    lLayout.addView(relResource);*/
        			    
	        			
	        			buttonRemoveFromFavorites = (Button) findViewById(R.id.buttonRmFavorites);
	        			buttonRemoveFromFavorites.setEnabled(true);
	        			buttonRemoveFromFavorites.setVisibility(View.VISIBLE);
	        			buttonRemoveFromFavorites.setOnClickListener(new OnClickListener() {
		        			public void onClick(View v) {
		        				AlertDialog.Builder builder = new AlertDialog.Builder(ServicoActivity.this);
		        				builder.setMessage(getString(R.string.realy_want_delete))
		        				       .setCancelable(false)
		        				       .setPositiveButton(getString(R.string.yes), new DialogInterface.OnClickListener() {
		        				           public void onClick(DialogInterface dialog, int id) {
		        				        	   Webservice w = Webservice.getInstance();
		       	        					try{
		       	        						w.delBookmark(bookmarkId);
		       	        					}catch (Exception e){
		       	        						return;
		       	        					}
		       	        					setResult(3);
		       	        					finish();
		       	        					Toast toast = Toast.makeText(ServicoActivity.this,"Remove Favorites", 3000);
		       	        					toast.show();
		        				           }
		        				       })
		        				       .setNegativeButton(getString(R.string.no), new DialogInterface.OnClickListener() {
		        				           public void onClick(DialogInterface dialog, int id) {
		        				        	   dialog.cancel();	        				       			
		        				           }
		        				       });
		        				AlertDialog alert = builder.create();
		        				alert.show();
		        				
		        			}
	        			});
	        			//button assign
	        			buttonAssign = (Button) findViewById(R.id.buttonAssign);
	        			buttonAssign.setEnabled(true);
	        			buttonAssign.setVisibility(View.VISIBLE);
	        			buttonAssign.setOnClickListener(new OnClickListener() {
		        			public void onClick(View v) {
		        				/*
		        				 * carregar
		        				 * disponibilidades do
		        				 * serviço
		        				 * 
		        				 */
		        				myProgressDialog = ProgressDialog.show(ServicoActivity.this,getString(R.string.loading), getString(R.string.getService), true); 
		        				Thread a = new Thread() {

		        					@Override
		        					public void run() {

		        					Webservice w = Webservice.getInstance();
		        					
		        					/**
		        					 * get
		        					 * disponibilidades
		        					 * do
		        					 * servico
		        					 * 
		        					 */
		        					GregorianCalendar d = new GregorianCalendar(2012,0,19);
									Date date = d.getTime();
									Disponibilidades.serviceBusyDays=new HashMap<Date, Integer>();
		        					Disponibilidades.serviceBusyDays.put((new GregorianCalendar(2012,0,19)).getTime(), new Integer(24));
		        					Disponibilidades.serviceBusyDays.put((new GregorianCalendar(2012,0,29)).getTime(), new Integer(4));
		        					
		        					messages.sendEmptyMessage(60);  
		        					}
		        				};
		        				a.start();
		        				    					
	        					
		        			}
	        			});
	        			
	        		}
	        		
	        		
	        		
	        		Log.d("Servico", "success");
	        		
	        	}
	        	else if(msg.what==-15){
	        		//token/auth error
	        		myProgressDialog.dismiss();
	        		Toast.makeText(ServicoActivity.this, getString(R.string.autentication_error), Toast.LENGTH_LONG).show();
	        	}
	        	else if(msg.what==30){
	        		Toast toast = Toast.makeText(ServicoActivity.this,"Assign Favorites"+serviceId, 3000);
					toast.show();
					
					//Service Day
					Intent intent = new Intent(ServicoActivity.this,
							ServiceDay.class);
					Bundle b = new Bundle();
					//id of service
					b.putLong("servicokey", serviceId);
					//id of bookmarker
					b.putLong("servicoyear", mYear);
					b.putLong("servicomonth", mMonth);
					b.putLong("servicoday", mDay);
					//b.putSerializable("service", (Serializable) servico);
					intent.putExtra("service", servico);
					intent.putExtras(b);
					startActivityForResult(intent, 0);
	        	}
	        	else if(msg.what==31){
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		       
	        		
	        	}
	        	else if(msg.what==60){
	        		myProgressDialog.dismiss();
	        		//go to service calendar
	        		Intent intent = new Intent(ServicoActivity.this,
							ServiceCalendar.class);
					Bundle b = new Bundle();
					//id of service
					b.putLong("servicokey", serviceId);
					//id of bookmarker
					b.putLong("bookmarkey", bookmarkId);
					intent.putExtra("service", servico);
					
					intent.putExtras(b);
					startActivityForResult(intent, 0); 
	        		  
	        	}
	        	else /*if(msg.what==-16)*/{
	        		//connection error
	        		myProgressDialog.dismiss();
	        		Toast.makeText(ServicoActivity.this, getString(R.string.impossiblereachtheserver), Toast.LENGTH_LONG).show();		       
	        		finish();
	        		//InternalStorage.goLoggin(ServicoActivity.this);
	        	}
	        	if(myProgressDialog.isShowing()) myProgressDialog.dismiss();
	        }
		};
	}
	
	/*
	@Override
	protected Dialog onCreateDialog(int id) {
		Calendar calendario = Calendar.getInstance();

		int ano = calendario.get(Calendar.YEAR);
		int mes = calendario.get(Calendar.MONTH);
		int dia = calendario.get(Calendar.DAY_OF_MONTH);

		switch (id) {
		case DATE_DIALOG_ID:
			return new DatePickerDialog(this, mDateSetListener, ano, mes,
					dia);
		}
		return null;
	}

	private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			mYear=year;
			mMonth=monthOfYear;
			mDay=dayOfMonth;
			ServicoActivity.this.messages.sendEmptyMessage(30);
		}
	};
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		Log.d("ServicoActivity", "actvityRequest "+requestCode+" "+resultCode);
		if(resultCode==2){
			Log.d("ServicoActivity", "finish");
			finish();
		}
		if(resultCode==4){
			Log.d("ServicoActivity", "finish");
			setResult(4);
			finish();
		}
		else{
			finish();
		}
		
	}*/
}
